package org.grow.present.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.grow.present.exception.NoAuthException;
import org.grow.present.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

//import javax.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Map;

/**
 * @Author: xwg
 * @CreateDate: 2023/9/20
 */
@Slf4j
@Component
//采用 spring的拦截器 效果与过滤器一致
public class AuthInterceptor implements HandlerInterceptor {
    public static Integer getCurrentUser(){
        return (Integer) RequestContextHolder.currentRequestAttributes().getAttribute("UID",0);
    }
    public static Integer getUID(){
        return (Integer) RequestContextHolder.currentRequestAttributes().getAttribute("UID",0);
    }
    public static String getCurrentToken(){
        return (String) RequestContextHolder.currentRequestAttributes().getAttribute("token",0);
    }
    @Autowired
    private JwtService jwtService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("拦截器生效 " + request.getRequestURI());
        String authorization = request.getHeader("Authorization");
        if (!StringUtils.hasText(authorization)) {
            throw new NoAuthException("请先登录");
        }
        System.out.println("token is " + authorization);
        String pureToken = authorization.replace("Bearer ", "");

        Map<String, Object> map = jwtService.parseToken(pureToken);
        System.out.println(" current user is " + map);
        Object username = map.get("UID");

        RequestContextHolder.currentRequestAttributes().setAttribute("UID",username,0);
        RequestContextHolder.currentRequestAttributes().setAttribute("token",pureToken,0);

        return true;
    }
}
